﻿using IBLL;
using IDAL;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class FileInfoBLL : IFileInfoBLL
    {
        private IFileInfoDAL _fileInfoDAL;

        public FileInfoBLL(IFileInfoDAL fileInfoDAL)
        {
            _fileInfoDAL = fileInfoDAL;
        }

        #region 创建一个文件上传的记录
        /// <summary>
        /// 创建一个文件上传的记录
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="extension"></param>
        /// <param name="length"></param>
        /// <param name="creatorId"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool CreateFileInfo(string fileId, string extension, long length, string creatorId, out string msg)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(fileId))
                {
                    msg = "文件id不能为空";
                    return false;
                }

                var entity = new FileInfo
                {
                    Id = fileId,
                    NewFileName = fileId,
                    Extension = extension,
                    Length = length,
                    Creator = creatorId,
                    Product_Type = GetContentType(extension),
                    CreateTime = DateTime.Now,
                };

                bool isOk = _fileInfoDAL.CreateEntity(entity);
                msg = isOk ? "成功" : "失败";
                return isOk;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return false;
            }
        }
        #endregion

        #region 根据id找文件记录
        /// <summary>
        /// 根据id找文件记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public FileInfo GetFileInfoById(string id)
        {
            var entity = _fileInfoDAL.GetEntities().FirstOrDefault(x => x.Id == id);

            return entity == null ? new FileInfo() : entity;
        }

        #endregion


        #region 根据后缀获取常见的MIME类型
        /// <summary>
        /// 根据后缀获取常见的MIME类型
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        public string GetContentType(string extension)
        {
            //字典
            Dictionary<string, string> mimeTypes = new Dictionary<string, string>
            {
                {".txt", "text/plain" },
                {".pdf", "application/pdf" },
                {".jpg","image/jpeg" },
                {".jpeg","image/jpeg" },
                {".png","image/png" },
                {".gif","image/gif" },
            };

            if (mimeTypes.ContainsKey(extension.ToLower()))
            {
                return mimeTypes[extension.ToLower()];
            }


            return "application/octet-stream";
        }
        #endregion

    }
}
